package com.test.config;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class DynamicDataSourceAspect {

    @Pointcut("@annotation(com.test.config.DynamicDataSource)")
    public void dynamicDataSourcePointCut() {
    }

    @Around("dynamicDataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        DynamicDataSource ds = method.getAnnotation(DynamicDataSource.class);
        if (ds == null) {
            DynamicDataSource classAnnotation = method.getDeclaringClass().getAnnotation(DynamicDataSource.class);
            if (classAnnotation == null) {
                DynamicDataSourceContextHolder.push("master");
            } else {
                DynamicDataSourceContextHolder.push(classAnnotation.value());
            }
        } else {
            DynamicDataSourceContextHolder.push(ds.value());
        }

        try {
            return point.proceed();
        } finally {
            DynamicDataSourceContextHolder.clear();
        }
    }
} 